package com.iseastar.guojiang.print;

import android.app.Service;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.IBinder;
import android.support.annotation.Nullable;

import com.iseastar.guojiang.app.AppCache;
import com.iseastar.guojiang.consts.MsgID;
import com.iseastar.guojiang.model.BluetoothDeviceBean;

import droid.frame.activity.HandlerMgr;
import printpp.printpp_yt.PrintPP_CPCL;

/**
 * Created by joker on 2017/8/1.
 * 用于连接蓝牙服务
 * 用activity或fragment连接蓝牙后，关闭activity或fragment的时候，蓝牙连接会中断，所以选择用服务来进行连接
 * 蓝牙连接只能建立一个PrintPP_CPCL对象，否则的话其他PrintPP_CPCL对象连接不上设备
 */
public class BluetoothConnectionService extends Service {

    public static PrintPP_CPCL iPrinter = null;
    private BluetoothDeviceBean bluetoothDeviceBean = null;

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        iPrinter = new PrintPP_CPCL();
    }

    @Override
    public void onStart(Intent intent, int startId) {
        super.onStart(intent, startId);
        bluetoothDeviceBean = AppCache.getBluetoothDeviceBean();
        if (bluetoothDeviceBean != null) {
            new connectionAysnc().execute();
        }
    }

    class connectionAysnc extends AsyncTask<Void, Void, Boolean> {

        @Override
        protected Boolean doInBackground(Void... params) {
            boolean fag = iPrinter.connect(bluetoothDeviceBean.getDeviceName(), bluetoothDeviceBean.getDeviceAddress());
            return fag;
        }

        @Override
        protected void onPostExecute(Boolean aBoolean) {
            super.onPostExecute(aBoolean);
            //打印机连接成功，通知页面响应的数据
            int status = 0;
            if (iPrinter.isConnected()) {
                status = 0;
            } else {
                status = -1;
            }
            HandlerMgr.sendMessage(MsgID.bluetoothconnectinstatus, status);
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        iPrinter.disconnect();
        iPrinter = null;
    }
}
